package com.common.image_loader;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.os.Handler;

import com.baidu.common.async_http.IResponseListener;
import com.baidu.common.async_http.IResponseProgressListener;
import com.baidu.common.async_http.ThreadPool;
import com.baidu.common.net.HttpEngine;
import com.baidu.common.net.HttpRequestData;
import com.baidu.common.net.NetworkErrorException;
import com.baidu.common.net.NetworkTimeoutException;
import com.baidu.common.net.ServerErrorException;
import com.japher.hackson.response.BaseResponse;
import com.japher.hackson.utils.Tools;

public class ImageRequestEx implements Runnable{

	IResponseListener listener = null;
	IResponseProgressListener progressListener;
	private Handler mHandler = new Handler();
	
	private String url;
	protected int length = -1;
	
	public ImageRequestEx(String url)
	{
		this.url=url;
	}
	
	
	public void StartRequest(IResponseListener aListener)
	{
		this.listener = aListener;
		ThreadPool.getInstance().execute(this);
	}

	public void setProgressListener(IResponseProgressListener progress)
	{
		progressListener = progress;
	}
	
	@Override
	public void run() 
	{
		HttpEngine httpEngine = null;
		BaseResponse response = null;
		
		httpEngine = HttpEngine.create();
		try {
			
			InputStream in = null;
			HttpRequestData data = new HttpRequestData();
			data.setUrl(url);
			data.setGet(true);
			data.setAppUrl(false);
			data.setGzip(false);
			data.setImageRequest(true);
			
			in = httpEngine.executeHttpRequest(data);
			length = (int) httpEngine.getLength();
			response = parse(in);
		}

		catch (NetworkTimeoutException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response = new BaseResponse();
			response.setStatusMessage("网络请求超时");

		} catch (NetworkErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response = new BaseResponse();
			response.setStatus(BaseResponse.ERR_CODE_NET);
			response.setStatusMessage("网络错误");

		} catch (ServerErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			response = new BaseResponse();
			if (!Tools.isEmpty(e.getErrordJson())) {
				response.setException(e);
			}
			response.setStatus(BaseResponse.ERR_CODE_SERVER);
			response.setStatusMessage("连接服务器错误");
		}
		
		if(listener!=null)
		{
			final BaseResponse r = response;
			mHandler.post(new Runnable()
			{
				@Override
				public void run()
				{
					listener.onRequestComplete(r);
				}
			});
			
		}
	}
	

	public BaseResponse parse(InputStream in) 
	{

		final ImageResponse imgResponse=new ImageResponse();
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		
		int count = 1024;
		byte []data=null;
		byte []temp=new byte[count];
		
		try 
		{
			int sum=0;
			while(true)
			{
				try 
				{
					int l = in.read(temp);
					if(l>0)
					{
						out.write(temp,0,l);
						publishProgress((sum+=l)*100/length);
					}
					else
					{
						break;
					}
				} 
				catch (Exception e) 
				{
					e.printStackTrace();break;
				}
			}
			data = out.toByteArray();
			out.close();
			imgResponse.setData(data);
			imgResponse.setSize(length);
			LocalImageManager.saveImage(Tools.getMD5(url), imgResponse.getData());
			
			if(data != null && data.length > 0)
			{
				imgResponse.setStatus(BaseResponse.RET_CODE_SUCCESS);
			}
		} 
		catch (IOException e) 
		{
			imgResponse.setStatus(-1);
			e.printStackTrace();
		}
		catch(OutOfMemoryError e)
		{
			imgResponse.setStatus(-1);
		}
		return imgResponse;
	}

	private void publishProgress(final int process)
	{
		if(progressListener != null)
		{
			mHandler.post(new Runnable()
			{
				@Override
				public void run()
				{
					progressListener.onProgress(process);
				}
			});
		}
	}
}
